package service.impl;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import entity.User;
import service.UserService;
import util.MD5Utils;
import util.MailUtils;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/9/27 21:58
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    @Override
    public int registerUser(User user) {
        int rows = 0;

        //激活邮件发送，邮件正文
        String content ="<a href='http://localhost:8080/MiShop/user?method=active&code="+user.getUcode()+"'>点击激活【Mi商城】</a>";

        boolean flag = MailUtils.sendMail(user.getEmail(), content, "激活邮件");
        System.out.println("邮件发送是否成功："+flag);

        rows = userDao.insertUser(user);
        return rows;
    }

    /**
     * 检测用户名是否存在
     *
     * @param username
     * @return
     */
    @Override
    public boolean checkUserName(String username) {
        //找不到返回null，找到了返回对象
        User user = userDao.findByUsername(username);
        //如果不为null无法注册
        if (user != null) {
            return false;
        }
        //user为null可以注册
        return true;
    }

    /**
     * 用户激活
     * @param code
     * @return
     */
    @Override
    public boolean active(String code) {
        //根据激活码查询用户对象
        User user = userDao.findByCode(code);
        if (user != null) {
            //调用dao的修改激活状态的方法
            userDao.updateStatus(user);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 登录验证
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username,String password) {
        //密码没加密，方便使用
        User unencryptedUser = userDao.findByUsernameAndPassword(username, password);
        if (unencryptedUser == null) {
            //通过用户名查询密码再加密比较
            User encryptedUser = userDao.findByUsername(username);
            if (encryptedUser != null && encryptedUser.getUpassword().equals(MD5Utils.md5(password))) {
                return encryptedUser;
            }

        }

        return unencryptedUser;
    }

}
